package com.gdit.zax.utils;

import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;





public class EmailUtil {
	
	
	
	public static boolean sendEmail(String to, String subject, String text) {
		String name = "1002819118";
		String pwd = "as1002819118";
		String mailhost = "smtp.qq.com";
		String from = "1002819118@qq.com";
		String mailer = "msgsend";
		
		LogUtil.print("send email:" + to + ">>" + subject+">>" + text);
		
		try {
		    /*
		     * Initialize the JavaMail Session.
		     */
		    Properties props = System.getProperties();
		    // XXX - could use Session.getTransport() and Transport.connect()
		    // XXX - assume we're using SMTP
		    
			props.put("mail.smtp.host", mailhost);
			props.put("mail.smtp.auth", "true");

			MyAuthenticator auth = new MyAuthenticator(name,pwd);
		    // Get a Session object
		    Session session = Session.getInstance(props, auth);
			session.setDebug(true);

		    /*
		     * Construct the message and send it.
		     */
		    Message msg = new MimeMessage(session);
		    
			msg.setFrom(new InternetAddress(from));

		    msg.setRecipients(Message.RecipientType.TO,InternetAddress.parse(to, false));
//		    if (cc != null)
//			msg.setRecipients(Message.RecipientType.CC,
//						InternetAddress.parse(cc, false));
//		    if (bcc != null)
//			msg.setRecipients(Message.RecipientType.BCC,
//						InternetAddress.parse(bcc, false));

		    msg.setSubject(subject);
			msg.setText(text);
		    

		    msg.setHeader("X-Mailer", mailer);
		    msg.setSentDate(new Date());

		    // send the thing off
			Transport transport= session.getTransport("smtp");
			transport.connect();
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
			
		    return true;
		} catch (Exception e) {
		    e.printStackTrace();
		}
		return false;
	}
	
	
}

class MyAuthenticator extends Authenticator {
	String name;
	String password;

	public MyAuthenticator(String name, String password) {
		this.name = name;
		this.password = password;

	}

	protected PasswordAuthentication getPasswordAuthentication() {
		System.out.println("getPasswordAuthentication!");
		return new PasswordAuthentication(name, password);
	}
}

